package task2;

import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Є число k та матриця чисел типу double. 
 * Знайти суму та добуток елементів k-го стовпця матриці.
 * 
 * @author Bondar K.
 *
 */
public class Task {
	private static final int K = 1;
	private static final int ROWS = 4;
	private static final int COLS = 4;
	
	public static void main(String[] args) {
		
		double[][] matrix = initRandomMatrix();
//		double[][] matrix = handJob();
		
		print(matrix);
		
		FutureTask<Double> sumTaskFuture = new FutureTask<Double>(new Sum(matrix));
		FutureTask<Double> mulTaskFuture = new FutureTask<Double>(new Mul(matrix));
		
		(new Thread(sumTaskFuture)).start();
		(new Thread(mulTaskFuture)).start();
		
		try {
			System.out.println("Sum of column: " + K + ": is " + sumTaskFuture.get());
			System.out.println("Mul of column: " + K + ": is " + mulTaskFuture.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		
		
	}

	private static double[][] handJob() {
		double[][] matrix = new double[ROWS][COLS];
		Scanner scanner = null;

		try {
			scanner = new Scanner(System.in);
			
			for (int i = 0; i < ROWS; i++) {
				for (int j = 0; j < COLS; j++) {
					System.out.printf("Please insert value for matrix[%d][%d]:\t", i, j);
					double value = scanner.nextDouble();
					matrix[i][j] = value;
				}
			}
		} finally {
			if (scanner != null) scanner.close();
		}
		
		return matrix;
	}

	private static void print(double[][] matrix) {
		for (int i = 0; i < ROWS; i++) {
			for (int j = 0; j < COLS; j++) {
				System.out.print(matrix[i][j] + "\t");
			}
			System.out.println();
		}
		
	}

	private static double[][] initRandomMatrix() {
		double[][] matrix = new double[ROWS][COLS]; 
		
		for (int i = 0; i < ROWS; i++) {
			matrix[i] = new double[COLS];
			for (int j = 0; j < COLS; j++) {
				matrix[i][j] = Math.random();
			}
		}
		return matrix;
	}
	
	static class Sum implements Callable<Double> {
		
		private double[][] matrix;

		public Sum(double[][] matrix) {
			this.matrix = matrix;
		}

		@Override
		public Double call() throws Exception {
			double sum = 0.0;
			for (int i = 0; i < ROWS; i++) {
				sum += matrix[i][K];
			}
			return sum;
		}
		
	}
	
	static class Mul implements Callable<Double> {
		
		private double[][] matrix;

		public Mul(double[][] matrix) {
			this.matrix = matrix;
		}

		@Override
		public Double call() throws Exception {
			double mul = 1.0;
			for (int i = 0; i < ROWS; i++) {
				mul *= matrix[i][K];
			}
			return mul;
		}
		
	}

}
